package com.fly.demo.job;

import java.util.Comparator;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.fly.demo.entity.Article;
import com.fly.demo.service.DataService;
import com.fly.demo.sse.SSEServer;

@Component
public class PushJob
{
    @Autowired
    DataService dataService;
    
    @Scheduled(initialDelay = 1000, fixedRate = 1000)
    public void run()
    {
        long index = (System.currentTimeMillis() / 1000) % 21;
        SSEServer.batchSendMessage(index * 5);
        if (index < 1)
        {
            // 推送访问量最小的
            List<Article> articles = dataService.getArticles();
            Article visit = new Random().ints(3, 0, articles.size()).mapToObj(i -> articles.get(i)).min(Comparator.comparing(Article::getViewCount)).get();
            SSEServer.batchSendMessage("json", ToStringBuilder.reflectionToString(visit, ToStringStyle.JSON_STYLE));
        }
    }
}
